package com.software.seakdream.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.software.seakdream.domain.Result;
import com.software.seakdream.entity.UserInfo;
import com.software.seakdream.service.UserInfoService;
import com.software.seakdream.utils.JWTUtils;
import com.software.seakdream.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.DateTimeException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/UserInfo")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;
    @PostMapping("/createUserInfo")
    public Result createUserInfo(UserInfo userInfo){
        String token;
        UserInfo create = userInfoService.createUserInfo(userInfo);
        Map<String,String> payload = new HashMap<>();
        payload.put("id", create.getUserId());
        payload.put("name", create.getUserName());
        //生成令牌
        token = JWTUtils.getToken(payload);
        return ResultUtils.success(create, token);
    }


    @PostMapping("/updatePoints")
    public void updatePoints(String userId, Integer points){
        userInfoService.updatePoints(userId,points);
    }
    @GetMapping("/queryUserByPhone")
    public Result queryUserByPhone(String phone){
        UserInfo query = userInfoService.queryUserByPhone(phone);
        String token;
        if (query == null){
            return ResultUtils.error("404","错误", null);
        }
        Map<String,String> payload = new HashMap<>();
        payload.put("id", query.getUserId());
        payload.put("name", query.getUserName());
        //生成令牌
        token = JWTUtils.getToken(payload);
        return ResultUtils.success(query, token);
    }

    @GetMapping("/getUserInfo")
    public
    Result getUserInfo(String id){

        UserInfo userInfo = userInfoService.getUserInfo(id);
        if (userInfo == null){
            return ResultUtils.error("404","错误", null);
        }
        return ResultUtils.success(userInfo);
    }
    @PostMapping("/setHeadshot")
    public void setHeadshot(String userId,String headshot){
        userInfoService.setHeadshot(userId,headshot);
    }

    @GetMapping("/setNickName")
    public void setNickName(String userId,String nickName){
        System.out.println("收到修改nickname");
        userInfoService.setNickName(userId,nickName);
    }

    @GetMapping("/setSex")
    public void setSex(String userId, String sex){
        userInfoService.setSex(userId,sex);
    }

    @GetMapping("/setDescription")
    public void setDescription(String userId,String description){
        userInfoService.setDescription(userId,description);
    }

    @GetMapping("/setBirthday")
    public void setBirthday(String userId,String birthday){
        userInfoService.setBirthday(userId,birthday);
    }

    @GetMapping("/setLocation")
    public void setLocation(String userId,String location){
        userInfoService.setLocation(userId,location);
    }
    @PostMapping("/login")
    public Result login(UserInfo user){
        log.info("用户名：[{}]", user.getUserName());
        log.info("密码：[{}]", user.getPassword());
        UserInfo userDB;
        String token;
        try {
            userDB = userInfoService.login(user);
            Map<String,String> payload = new HashMap<>();
            payload.put("id", userDB.getUserId());
            payload.put("name", userDB.getUserName());
            //生成令牌
            token = JWTUtils.getToken(payload);
        }catch (Exception e){
            return ResultUtils.error("404","错误", null);
        }
        return ResultUtils.success(userDB, token);
    }

    @PostMapping("/test")
    public Result test(HttpServletRequest request){

        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtils.verify(token);
        log.info("用户id:[{}]", verify.getClaim("id").asString());
        log.info("用户名:[{}]", verify.getClaim("name").asString());
        return ResultUtils.success(verify.getClaim("id").asString(), token);
    }

    @PostMapping("/openVip")
    public void openVip(String userId,Integer vipTime ){
        UserInfo userInfo = userInfoService.getUserInfo(userId);
        System.out.println(vipTime);
        //用户为非会员时
        if(!userInfo.getIfVip().equals("1")){
            Date date=new Date();
            userInfoService.updateIfVip(userId,"1");
            userInfoService.updateBeginTime(userId,date);
            Calendar cal = Calendar.getInstance();
            // 设置开始时间
            cal.setTime(date);
            //增加或减少num天
            cal.add(Calendar.DATE,vipTime);
            //cal.add(Calendar.DATE, -10);//减10天
            //cal.add(Calendar.DATE, 2);//加2天
            Date newDate = cal.getTime();
            userInfoService.updateEndTime(userId,newDate);
        }
        //用户为会员时
        else{
            Date date=userInfo.getVipEndTime();
            //会员未过期
            if (date.after(new Date())){
                Calendar cal = Calendar.getInstance();
                // 设置开始时间
                cal.setTime(date);
                //增加或减少num天
                cal.add(Calendar.DATE,vipTime);
                //cal.add(Calendar.DATE, -10);//减10天
                //cal.add(Calendar.DATE, 2);//加2天
                Date newDate = cal.getTime();
                userInfoService.updateEndTime(userId,newDate);
                userInfoService.updateEndTime(userInfo.getUserId(),newDate);
            }
            //会员已过期
            else {
                userInfoService.updateBeginTime(userInfo.getUserId(),date);
                userInfoService.updateEndTime(userInfo.getUserId(),new Date(date.getTime()+(long)vipTime*24*60*60*1000));
            }
        }
    }
}
